<script lang="ts" setup name="AddProject">
import { ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { _ } from 'iking-utils'
import type { addProParams, dependency, dependencyData } from '../interface'
import {
  addProject,
  editProject,
  getDependency,
  getProjectById
} from '@/MainApp/apis/manage-design'
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: () => null
  },
  title: {
    type: String,
    default: '新建功能'
  }
})
const emits = defineEmits<{
  (event: 'cancel'): void
  (event: 'update:visible', value: boolean): void
  (event: 'confirm', data: object): void
}>()
const { msgSuccess, msgError } = useMessage()
const { t } = useConfig()
const { lenContent, lenName } = useLength()
const formKey = {
  name: '',
  basePackageName: '',
  groupId: '',
  description: '',
  artifact: '',
  dependencies: [],
  projectType: 'Maven Project',
  projectPackageName: ''
}
const projectFormRef = ref()
const projectForm = ref(formKey)
const loading = ref(false)
const userRules = {
  name: [{
    required: true,
    trigger: 'blur',
    message: '请输入工程名称'
  }
  ],
  groupId: [{
    required: true,
    trigger: 'blur',
    message: '请输入Group'
  }
  ],
  basePackageName: [{
    required: true,
    trigger: 'change',
    validator: (rule: any, value: any, cb: any) => {
      const str = /^[a-z0-9.]*$/
      if (!value)
        cb('请输入基础包名')

      if (!str.test(value))
        cb('此处只允许使用小写英文字母，数字，点')
      else
        cb()
    }
  }
  ],
  artifact: [{
    required: true,
    trigger: 'change',
    validator: (rule: any, value: any, cb: any) => {
      const str = /^[a-z0-9.-]*$/
      if (!value)
        cb('请输入Artifact')
      if (!str.test(value))
        cb('此处只允许使用小写英文字母，数字，点，中划线')
      else
        cb()
    }
  }
  ]
}

const dVisible = ref(false)
const searchGroup = ref('')
const checkedList = ref<Array<dependency>>([])
const dependencyList = ref<Array<dependencyData>>([])
const dependencyCount = ref<number>(0)
let searchList: Array<any> = []
const getDependencyList = async () => {
  const {
    success,
    data: { count, dependencyGroupList }
  } = await getDependency()
  if (success) {
    if (props.editData && projectForm.value.dependencies) {
      dependencyList.value = dependencyGroupList.map((item: any) => {
        item.dependencyList = item.dependencyList.map((ele: any) => {
          const data = projectForm.value.dependencies?.find(
            (e: any) => e === ele.name
          )
          if (data) {
            ele.checked = true
            checkedList.value.push(ele)
          }

          return ele
        })
        return item
      })
    }
    else {
      dependencyList.value = dependencyGroupList.map((item: any) => {
        item.dependencyList = item.dependencyList.map((ele: any) => {
          if (ele.checked)
            checkedList.value.push(ele)
          return ele
        })
        return item
      })
    }
    dependencyCount.value = count
    searchList = dependencyList.value
  }
}
const handCancel = () => {
  dVisible.value = false
  projectFormRef.value?.resetFields()
  emits('update:visible', false)
}
const handClosed = () => {
  dVisible.value = false
  projectFormRef.value?.resetFields()
  emits('cancel')
  handCancel()
}

const handConfirm = async (str: any) => {
  projectFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      const dependenciesArray = checkedList.value.map(item => {
        return item.name
      })
      const params: addProParams = {
        ...projectForm.value,
        scaffoldType: 'PROJECT',
        scaffoldTypeName: '工程',
        dependencies: dependenciesArray
      }
      let data
      if (props.editData) {
        params.id = props.editData.id
        data = await editProject(params)
      }
      else {
        data = await addProject(params)
      }
      if (data?.success) {
        emits('confirm', {
          ...projectForm.value,
          goFun: str,
          projectId: data.data || ''
        })
        loading.value = false
        handCancel()
        msgSuccess(data?.msg)
      }
      else {
        loading.value = false
        msgError(data?.msg)
      }
    }
  })
}
const groupChecked = (list: dependency): any => {
  // groupList.value[index].group[i].checked = list.checked;
  if (list.checked) {
    const data = checkedList.value.find(item => item.name === list.name)
    !data && checkedList.value.push(list)
  }
  else {
    checkedList.value.forEach((item, index) => {
      if (item.name === list.name)
        checkedList.value.splice(index, 1)
    })
  }
}
const clickSearchTable = () => {
  if (searchGroup.value) {
    dependencyList.value = searchList.filter(
      item => item.groupName?.indexOf(searchGroup.value) !== -1
    )
  }
  else {
    dependencyList.value = searchList
  }
}
const basePackageChange = _.debounce(value => {
  if (value) {
    if (projectForm.value.artifact) {
      const data = projectForm.value.artifact.split('-')
      projectForm.value.projectPackageName = `${value}.${data.join('.')}`
    }
  }
}, 200)
const artifactChange = _.debounce(value => {
  if (value) {
    if (projectForm.value.basePackageName) {
      const data = value.split('-')
      projectForm.value.projectPackageName = `${projectForm.value.basePackageName}.${data.join('.')}`
    }
  }
}, 200)
watch(
  () => props.visible,
  async visible => {
    if (visible) {
      if (props.editData) {
        const { success, data } = await getProjectById(props.editData.id)
        if (success)
          projectForm.value = { ...data }

        projectForm.value.projectType = 'Maven Project'
      }
      await getDependencyList()
      dVisible.value = true
    }
    else {
      projectForm.value = { ...formKey }
      dVisible.value = false
      checkedList.value = []
      dependencyCount.value = 0
    }
  }
)
</script>

<template>
  <el-dialog
    v-model="dVisible"
    class="form-design"
    :title="props.editData ? '编辑工程' : '新建工程'"
    width="1200px"
    align-center
    draggable
    :close-on-click-modal="false"
    @closed="handClosed"
  >
    <div class="manage-design">
      <el-form
        ref="projectFormRef"
        :model="projectForm"
        :rules="userRules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="24" class="elcolTitle">
            <p class="projectTitle">基本信息</p>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工程名称" prop="name">
              <el-input
                v-model.trim="projectForm.name"
                clearable
                :maxlength="lenName"
                show-word-limit
                placeholder="请输入工程名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工程构建方式" prop="projectType">
              <el-radio-group v-model="projectForm.projectType">
                <el-radio-button label="Maven Project" />
                <el-radio-button disabled label="Gradle Project" />
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Group" prop="groupId">
              <el-input
                v-model.trim="projectForm.groupId"
                clearable
                placeholder="公司或者组织的唯一标识，例如：com.example"
                maxlength="64"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Artifact" prop="artifact">
              <el-input
                v-model.trim="projectForm.artifact"
                clearable
                placeholder="项目的唯一ID，例如：demo"
                maxlength="64"
                show-word-limit
                @input="artifactChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="基础包名" prop="basePackageName">
              <el-input
                v-model.trim="projectForm.basePackageName"
                clearable
                placeholder="同artifact使用.号拼接作为工程的包名，例如：com.example.demo"
                maxlength="256"
                show-word-limit
                @input="basePackageChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工程包名" prop="projectPackageName">
              <el-input
                v-model.trim="projectForm.projectPackageName"
                clearable
                :maxlength="lenName"
                show-word-limit
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目描述" prop="description">
              <el-input
                v-model.trim="projectForm.description"
                clearable
                placeholder="请输入项目描述"
                type="textarea"
                :maxlength="lenContent"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <el-col :span="24" class="elcolTitle">
          <p class="projectTitle">组件依赖</p>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" class="group-rely">
          <el-input
            v-model.trim="searchGroup"
            class="m-2 w-50"
            placeholder="请输入关键字"
            clearable
            @clear="clickSearchTable"
          >
            <template #append>
              <el-button :icon="Search" @click="clickSearchTable" />
            </template>
          </el-input>
          <div class="group-head">
            <p> {{ `待选组件(${checkedList.length}/${dependencyCount})` }}</p>
          </div>
          <div class="coll-group-head">
            <el-collapse
              v-for="(item, index) in dependencyList"
              :key="index"
              class="group-list"
              accordion
            >
              <el-collapse-item
                :key="index"
                class="group-dev"
                name="item.id"
                :title="item.groupName"
              >
                <div
                  v-for="(list, i) in item.dependencyList"
                  :key="i"
                  class="group-con"
                >
                  <el-checkbox
                    v-model="list.checked"
                    @change="groupChecked(list)"
                  />
                  <div class="group-right">
                    <p>{{ list.componentName }}</p>
                    <el-tooltip effect="dark">
                      <template #content>
                        <div class="cen-text">
                          {{ list.componentDescription }}
                        </div>
                      </template>
                      <p class="s-text">{{ list.componentDescription }}</p>
                    </el-tooltip>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-col>
        <el-col :span="12" class="group-rely">
          <div class="group-head">
            <p>{{ `已选组件(${checkedList.length})` }}</p>
          </div>
          <div class="coll-group-head">
            <div
              v-for="(list, i, key) in checkedList"
              :key="key"
              class="group-con"
            >
              <el-checkbox
                v-model="list.checked"
                @change="groupChecked(list)"
              />
              <div class="group-right">
                <p>{{ list.componentName }}</p>
                <el-tooltip effect="dark">
                  <template #content>
                    <div class="cen-text">{{ list.componentDescription }}</div>
                  </template>
                  <p class="s-text">{{ list.componentDescription }}</p>
                </el-tooltip>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="loading" @click="handCancel">{{ t("action.cancel") }}</el-button>
        <el-button :loading="loading" type="primary" @click="handConfirm('')">
          {{ t("action.sure") }}
        </el-button>
        <el-button
          v-show="!props.editData"
          type="primary"
          :loading="loading"
          @click="handConfirm('fun')"
        >
          保存并创建功能
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.cen-text {
  max-width: 400px;
}

.manage-design {
  padding: 15px;

  .el-dialog__body {
    max-height: 85vh !important;
    padding: 0 !important;
    overflow: auto !important;
    flex: 1;
  }

  .elcolTitle {
    padding: 15px;
    border-bottom: 1px solid #e5e5e5;
    margin-bottom: 15px;

    .projectTitle {
      font-size: 16px;
      font-weight: 400;
      color: #333;
      padding-left: 10px;
      border-left: 5px solid #409eff;
    }
  }
}

.coll-group-head {
  max-height: 400px;
  overflow: auto;
  padding: 10px;
}

.group-rely {
  padding: 20px 30px;
  border-right: 1px solid #e5e5e5;

  .group-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
  }

  .group-list {
    border: none !important;

    .group-dev {
      .el-collapse-item__header {
        border: none !important;

        :deep(.el-collapse-item__arrow) {
          margin: 0 8px 0 10px !important;
        }
      }
    }
  }

  .group-con {
    height: 100px;
    border: 1px solid #e5e5e5;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: 5px 20px;
    margin: 5px 0;

    .group-right {
      margin-left: 15px;
      display: flex;
      align-items: flex-start;
      justify-content: center;
      flex-direction: column;

      .s-text {
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
    }
  }
}
</style>
